package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDto;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Resource
    private CategoryBrandService categoryBrandService;
    @Resource
    private BrandMapper brandMapper;

    //新增品牌表与中间表
    @Transactional
    @Override
    public void saveBrand(BrandDto brandDto) {
        Brand brand = brandDto.toEntity(Brand.class);
        boolean success = this.save(brand);//新增品牌表
        if (!success) {
            throw new LyException(500, "新增品牌失败!");
        }
        //新增中间表
        Long brandId = brand.getId();
        List<Long> categoryIds = brandDto.getCategoryIds();//获取分类id集合
        List<CategoryBrand> categoryBrands = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }
        categoryBrandService.saveBatch(categoryBrands);
    }

    //根据ID删除品牌
    @Transactional
    @Override
    public void deleteBrandById(Long id) {
        boolean success1 = removeById(id);//删除品牌
        if (!success1) {
            throw new LyException(500, "删除品牌表失败!");
        }
        //删除中间表
        boolean success2 = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        if (!success2) {
            throw new LyException(500, "删除品牌失败!删除中间表失败");
        }
    }

    //更新品牌
    @Override
    public void updateBrand(BrandDto brandDto) {
        //修改品牌表
        boolean success1 = updateById(brandDto.toEntity(Brand.class));
        if (!success1) {
            throw new LyException(500, "更新品牌失败!");
        }
        //删除中间表
        boolean success2 = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDto.getId()));
        if (!success2) {
            throw new LyException(500, "更新品牌失败!删除中间表失败");
        }
        //新增中间表
        Brand brand = brandDto.toEntity(Brand.class);
        Long brandId = brand.getId();
        List<Long> categoryIds = brandDto.getCategoryIds();//获取分类id集合
        List<CategoryBrand> categoryBrands = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }
        categoryBrandService.saveBatch(categoryBrands);
    }

    //分页查询品牌
    @Override
    public PageDTO<BrandDto> queryBrandByPage(Integer page, Integer rows, String key) {
        //1.分页信息的健壮性处理
        page = Math.max(page, 1);//当前页码要大于1
        rows = Math.max(rows, 1);
        //2.分页
        //3.判断查询key是否存在
        boolean isKeyExists = StringUtils.isNotBlank(key);//不为空
        //4.如果key存在，添加like和eq的查询条件，否则不添加
        Page<Brand> brandPage = this.query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(new Page<>(page, rows));
        //5.封装结果
        List<Brand> list = brandPage.getRecords();//品牌的当前页数据
        return new PageDTO<>(brandPage.getTotal(), brandPage.getPages(), BrandDto.convertEntityList(list));
    }

    //根据分类id查询品牌集合
    @Override
    public List<BrandDto> queryBrandsByCategoryId(Long id) {
        List<Brand> brands = brandMapper.queryBrandsByCategoryId(id);
        return BrandDto.convertEntityList(brands);
    }


}
